#include "sg90.h"

int work(int port, int *fd){
	*fd = socket(AF_INET, SOCK_STREAM, 0);
	if(*fd < 0){
		perror("socket");
		return 0;
	}
	
	int opt = 1;
    	if (setsockopt(*fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
		perror("setsockopt");
		close(*fd);
		return -1;
    	}
	
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = inet_addr("192.168.100.98");
	//绑定
	if(bind(*fd, (struct sockaddr *)&addr, sizeof(addr))){
		perror("bind");
	}
	//设置监听，模式
	if(listen(*fd, 3)){
		perror("listen");
	}
	//接受请求
	struct sockaddr_in cli_addr;
	socklen_t len = sizeof(cli_addr);
	int fbap = accept(*fd, (struct sockaddr *)(&cli_addr), &len);
	if(fbap < 0){
		perror("accept");
		return 0;
	}
	printf("accept ok\n");

	return fbap;
}
void control_sg90(int connfd){
	char buf[32]={0};
	 int serial_fd;
	while(1){
		memset(buf, 0, sizeof(buf));
		int read_buf=recv(connfd,buf,sizeof(buf),0);
		if(read_buf<0)//错误
		{
		    perror("recv");
		    close(connfd);
		    continue;
		}
		printf("recv:buf=%s\n",buf);
		serial_fd =serial_open("/dev/ttyUSB0");
		if (serial_fd < 0) {
		    perror("open serial");
		    continue;
		}
		serial_config(serial_fd);//配置串口

		if(read_buf> 0 && strncmp(buf, "1\n", 3) == 0)
		{
		    printf("get serial MSG\n");
		    char buf1[2];
		    sprintf(buf1, "%d", 0); // 将数字0转换为字符串
		    serial_write(serial_fd,buf);
		    printf("serial send success\n");
		}
		close(serial_fd);
	}
}


